/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.company.impl;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.auth.impl.Department;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.PlatformService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.JEUUID;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.exception.AccountException;
import com.je.rbac.exception.DepartmentUserException;
import com.je.rbac.rpc.AccountRpcService;
import com.je.rbac.service.IconType;
import com.je.rbac.service.account.RbacAccountService;
import com.je.rbac.service.company.RbacDepartmentService;
import com.je.rbac.service.company.RbacDepartmentUserService;
import com.je.rbac.service.grant.RbacGrantTreeService;
import com.je.rbac.service.organization.OrgType;
import com.je.rbac.service.role.RbacAccountRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RbacDepartmentUserServiceImpl implements RbacDepartmentUserService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private RbacDepartmentService rbacDepartmentService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;
    @Autowired
    private BeanService beanService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private AccountRpcService accountRpcService;
    @Autowired
    private RbacGrantTreeService rbacGrantTreeService;
    @Autowired
    private RbacDepartmentUserService rbacDepartmentUserService;
    @Autowired
    protected PlatformService manager;
    @Autowired
    private RbacAccountService rbacAccountService;
    @Autowired
    private RbacAccountRoleService rbacAccountRoleService;

    @Override
    public void loadParam(BaseMethodArgument param) {
        String jQuery = param.getjQuery();
        JSONObject object = new JSONObject();
        if(!JSON.isValidObject(jQuery)){
            return;
        }
        object = JSONObject.parseObject(jQuery);
        JSONArray array = (JSONArray) object.get("custom");
        for (int i = 0; i < array.size(); i++) {
            JSONObject newObject = (JSONObject) array.get(i);
            JSONArray arrayOne = (JSONArray) newObject.get("value");

            JSONObject arrayOne_1 = (JSONObject) arrayOne.get(0);
            if (arrayOne_1.get("code").equals("SY_PATH") || (arrayOne_1.get("code").equals("JE_RBAC_DEPTUSER_ID") && !arrayOne_1.get("value").equals("ROOT"))) {
                String val = "";
                String type = "like";
                if (arrayOne_1.get("code").equals("SY_PATH")) {
                    String strValue = arrayOne_1.get("value").toString();
                    val = strValue.substring(strValue.lastIndexOf("/") + 1, strValue.length());
                } else if (arrayOne_1.get("code").equals("JE_RBAC_DEPTUSER_ID")) {
                    String strValue = arrayOne_1.get("value").toString();
                    JSONArray jsonArrVal = JSONArray.parseArray(strValue);
                    type = "in";
                    val = jsonArrVal.toJSONString();
                }

                JSONObject arrayTwo = new JSONObject();
                arrayTwo.put("cn", "or");
                arrayTwo.put("type", type);
                arrayTwo.put("code", "JE_RBAC_DEPARTMENT_ID");
                arrayTwo.put("value", val);
                arrayOne.add(arrayTwo);

                JSONObject arraySysCompany = new JSONObject();
                arraySysCompany.put("cn", "or");
                arraySysCompany.put("type", type);
                arraySysCompany.put("code", "SY_COMPANY_ID");
                arraySysCompany.put("value", val);
                arrayOne.add(arraySysCompany);

                JSONObject arraySysGroupCompany = new JSONObject();
                arraySysGroupCompany.put("cn", "or");
                arraySysGroupCompany.put("type", type);
                arraySysGroupCompany.put("code", "SY_GROUP_COMPANY_ID");
                arraySysGroupCompany.put("value", val);
                arrayOne.add(arraySysGroupCompany);
                break;
            }
        }
        param.setjQuery(object.toJSONString());
    }

    @Override
    public boolean checkUserCodeUnique(DynaBean dynaBean, List<DynaBean> rbacUserList) {
        long count = 0;
        if (Strings.isNullOrEmpty(dynaBean.getStr("JE_RBAC_USER_ID"))) {
            count = rbacUserList.stream().filter((user -> user.getStr("USER_CODE").equals(dynaBean.getStr("USER_CODE")))).count();
//            count = metaService.countBySql(ConditionsWrapper.builder().table("JE_RBAC_USER").eq("USER_CODE", dynaBean.getStr("USER_CODE")));
        } else {
            count = rbacUserList.stream().filter(user -> !user.getStr("JE_RBAC_USER_ID").equals(dynaBean.getStr("JE_RBAC_USER_ID")))
                    .filter(user -> user.getStr("USER_CODE").equals(dynaBean.getStr("USER_CODE"))).count();
//            count = metaService.countBySql(ConditionsWrapper.builder().apply("SELECT * FROM JE_RBAC_USER WHERE JE_RBAC_USER_ID != {0} AND (USER_CODE = {1})",dynaBean.getStr("JE_RBAC_USER_ID"),dynaBean.getStr("USER_CODE")));
        }
        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkUserCodeUnique(DynaBean dynaBean) {
        long count = 0;
        if (Strings.isNullOrEmpty(dynaBean.getStr("JE_RBAC_USER_ID"))) {
            count = metaService.countBySql(ConditionsWrapper.builder().table("JE_RBAC_USER").eq("USER_CODE", dynaBean.getStr("USER_CODE")));
        } else {
            count = metaService.countBySql(ConditionsWrapper.builder().apply("SELECT * FROM JE_RBAC_USER WHERE JE_RBAC_USER_ID != {0} AND (USER_CODE = {1})", dynaBean.getStr("JE_RBAC_USER_ID"), dynaBean.getStr("USER_CODE")));
        }
        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkUserPhoneUnique(DynaBean dynaBean) {
        long count = 0;
        if (Strings.isNullOrEmpty(dynaBean.getStr("JE_RBAC_USER_ID"))) {
            count = metaService.countBySql(ConditionsWrapper.builder().table("JE_RBAC_USER").eq("USER_PHONE", dynaBean.getStr("USER_PHONE")));
        } else {
            count = metaService.countBySql(ConditionsWrapper.builder().apply("SELECT * FROM JE_RBAC_USER WHERE JE_RBAC_USER_ID != {0} AND (USER_PHONE = {1})", dynaBean.getStr("JE_RBAC_USER_ID"), dynaBean.getStr("USER_PHONE")));
        }
        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkUserMailUnique(DynaBean dynaBean) {
        long count = 0;
        if (Strings.isNullOrEmpty(dynaBean.getStr("JE_RBAC_USER_ID"))) {
            count = metaService.countBySql(ConditionsWrapper.builder().table("JE_RBAC_USER").eq("USER_MAIL", dynaBean.getStr("USER_MAIL")));
        } else {
            count = metaService.countBySql(ConditionsWrapper.builder().apply("SELECT * FROM JE_RBAC_USER WHERE JE_RBAC_USER_ID != {0} AND (USER_MAIL = {1})", dynaBean.getStr("JE_RBAC_USER_ID"), dynaBean.getStr("USER_MAIL")));
        }
        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public DynaBean doSave(DynaBean viewDeptUserBean) throws DepartmentUserException {
        String departmentId = viewDeptUserBean.getStr("JE_RBAC_DEPARTMENT_ID");

        DynaBean deptBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", departmentId));
        if (deptBean == null) {
            throw new DepartmentUserException("请确认部门是否存在！");
        }
        if (deptBean.getStr("SY_STATUS").equals("0")) {
            throw new DepartmentUserException("部门状态已禁用,请确认！");
        }

        DynaBean userBean = new DynaBean("JE_RBAC_USER", false);
        DynaBean userBeanTable = beanService.getResourceTable("JE_RBAC_USER");
        List<DynaBean> userColumns = userBeanTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
        for (DynaBean eachColumnBean : userColumns) {
            if (viewDeptUserBean.containsKey(eachColumnBean.getStr("TABLECOLUMN_CODE"))) {
                userBean.set(eachColumnBean.getStr("TABLECOLUMN_CODE"), viewDeptUserBean.get(eachColumnBean.getStr("TABLECOLUMN_CODE")));
            }
        }
        commonService.buildModelCreateInfo(userBean);
        userBean.set("SY_ORG_ID", deptBean.getStr("SY_ORG_ID"));
        metaService.insert(userBean);

        List<Map<String, Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPTUSER WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
        if (countList.size() <= 0) {
            countList = metaService.selectSql("SELECT MAX(DEPARTMENT_USER_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPARTMENT WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
        }
        int count = Integer.valueOf(countList.get(0).get("MAX_COUNT").toString());

        DynaBean deptUserBeanTable = beanService.getResourceTable("JE_RBAC_DEPTUSER");
        List<DynaBean> deptUserColumns = deptUserBeanTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
        DynaBean deptUserBean = new DynaBean("JE_RBAC_DEPTUSER", false);
        for (DynaBean eachColumnBean : deptUserColumns) {
            if (viewDeptUserBean.containsKey(eachColumnBean.getStr("TABLECOLUMN_CODE"))) {
                deptUserBean.set(eachColumnBean.getStr("TABLECOLUMN_CODE"), viewDeptUserBean.get(eachColumnBean.getStr("TABLECOLUMN_CODE")));
            }
        }
        deptUserBean.set("JE_RBAC_USER_ID", userBean.getStr("JE_RBAC_USER_ID"));
        deptUserBean.set("JE_RBAC_DEPARTMENT_ID", departmentId);
        deptUserBean.setStr("SY_GROUP_COMPANY_ID", deptBean.getStr("SY_GROUP_COMPANY_ID"));
        deptUserBean.setStr("SY_GROUP_COMPANY_NAME", deptBean.getStr("SY_GROUP_COMPANY_NAME"));
        deptUserBean.set("DEPTUSER_MAIN_CODE", "1");
        deptUserBean.set("DEPTUSER_MAIN_NAME", "主部门");
        deptUserBean.set("SY_STATUS", "0");
        deptUserBean.set("SY_ORDERINDEX", count + 1);
        commonService.buildModelCreateInfo(deptUserBean);
        metaService.insert(deptUserBean);

        //同步所属部门主管领导信息
        if (!Strings.isNullOrEmpty(deptUserBean.getStr("DEPTUSER_SFZG_CODE"))) {
            if (Strings.isNullOrEmpty(deptBean.getStr("DEPARTMENT_MAJOR_ID")) && deptUserBean.getStr("DEPTUSER_SFZG_CODE").equals("1")) {
                //更新部门主管信息
                metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", userBean.getStr("JE_RBAC_USER_ID"), userBean.getStr("USER_NAME"), departmentId);
            } else if (!Strings.isNullOrEmpty(deptBean.getStr("DEPARTMENT_MAJOR_ID"))) {
                //判断是否是主管,若 是主管
                if (deptUserBean.getStr("DEPTUSER_SFZG_CODE").equals("1")) {
                    //判断当前人是否在主管中，不在则追加
                    if (!deptBean.getStr("DEPARTMENT_MAJOR_ID").contains(userBean.getStr("JE_RBAC_USER_ID"))) {
                        List<String> majorIdList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_ID").split(ArrayUtils.SPLIT));
                        List<String> newMajorIdList = new ArrayList(majorIdList);
                        newMajorIdList.add(userBean.getStr("JE_RBAC_USER_ID"));
                        List<String> majorNameList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_NAME").split(ArrayUtils.SPLIT));
                        List<String> newMajorNameList = new ArrayList(majorNameList);
                        newMajorNameList.add(userBean.getStr("USER_NAME"));
                        metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", StringUtils.join(newMajorIdList, ","), StringUtils.join(newMajorNameList, ","), departmentId);
                    }
                }

            }
        }

        //同步创建账号 状态默认为 禁用
        JSONArray array = new JSONArray();
        JSONObject userObj = new JSONObject();
        userObj.put("status", "0");
        userObj.put("departmentId", departmentId);
        userObj.put("userId", deptUserBean.getStr("JE_RBAC_USER_ID"));
        userObj.put("mainCode", deptUserBean.getStr("DEPTUSER_MAIN_CODE"));
        array.add(userObj);
        openAccount(array.toJSONString());
        return metaService.selectOne("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId).eq("JE_RBAC_USER_ID", userBean.getStr("JE_RBAC_USER_ID")));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public DynaBean doUpdate(DynaBean viewDeptUserBean) throws DepartmentUserException, AccountException {
        String departmentId = viewDeptUserBean.getStr("JE_RBAC_DEPARTMENT_ID");
        String userId = viewDeptUserBean.getStr("JE_RBAC_USER_ID");

        DynaBean deptBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", departmentId));
        if (deptBean == null) {
            throw new DepartmentUserException("请确认存在此部门！");
        }

        DynaBean userBean = metaService.selectOne("JE_RBAC_USER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userId));
        if (userBean == null) {
            throw new DepartmentUserException("请确认存在此人员！");
        }

        String originalRoleIds = userBean.getStr("USER_ROLE_ID");

        DynaBean userBeanTable = beanService.getResourceTable("JE_RBAC_USER");
        List<DynaBean> userColumns = userBeanTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
        for (DynaBean eachColumnBean : userColumns) {
            if (viewDeptUserBean.containsKey(eachColumnBean.getStr("TABLECOLUMN_CODE"))) {
                userBean.set(eachColumnBean.getStr("TABLECOLUMN_CODE"), viewDeptUserBean.get(eachColumnBean.getStr("TABLECOLUMN_CODE")));
            }
        }
        commonService.buildModelModifyInfo(userBean);
        //若用户名称发生修改，则同步更新全局该用户名称
        updateUserName(viewDeptUserBean);

        metaService.update(userBean);
        //判断是否有账号，若有同步账号相关信息
        DynaBean account = metaService.selectOne("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().eq("USER_ASSOCIATION_ID", userBean.getStr("JE_RBAC_USER_ID")));
        if (account != null) {
            //校验唯一性
            rbacAccountService.checkAccountCodeUnique(account.getStr("JE_RBAC_ACCOUNT_ID"), viewDeptUserBean.getStr("USER_CODE"));
            rbacAccountService.checkAccountPhoneUnique(account.getStr("JE_RBAC_ACCOUNT_ID"), viewDeptUserBean.getStr("USER_PHONE"));
            rbacAccountService.checkAccountEmailUnique(account.getStr("JE_RBAC_ACCOUNT_ID"), viewDeptUserBean.getStr("USER_MAIL"));

            metaService.executeSql(
                    "UPDATE JE_RBAC_ACCOUNT SET ACCOUNT_CODE={0} , ACCOUNT_NAME={1},ACCOUNT_PHONE={2},ACCOUNT_MAIL={3},ACCOUNT_AVATAR={4} , ACCOUNT_SEX={5} WHERE JE_RBAC_ACCOUNT_ID ={6}",
                    userBean.getStr("USER_CODE"),
                    userBean.getStr("USER_NAME"),
                    userBean.getStr("USER_PHONE"),
                    userBean.getStr("USER_MAIL"),
                    userBean.getStr("USER_AVATAR"),
                    userBean.getStr("USER_SEX_CODE"),
                    account.getStr("JE_RBAC_ACCOUNT_ID"));
        }


        DynaBean deptUserBeanTable = beanService.getResourceTable("JE_RBAC_DEPTUSER");
        List<DynaBean> deptUserColumns = deptUserBeanTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
        DynaBean deptUserBean = new DynaBean("JE_RBAC_DEPTUSER", false);
        for (DynaBean eachColumnBean : deptUserColumns) {
            if (viewDeptUserBean.containsKey(eachColumnBean.getStr("TABLECOLUMN_CODE"))) {
                deptUserBean.set(eachColumnBean.getStr("TABLECOLUMN_CODE"), viewDeptUserBean.get(eachColumnBean.getStr("TABLECOLUMN_CODE")));
            }
        }
        //处理人员排序字段
        DynaBean deptUser = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder().eq("JE_RBAC_DEPTUSER_ID", viewDeptUserBean.getStr("JE_RBAC_DEPTUSER_ID")));
        if (!departmentId.equals(deptUser.getStr("JE_RBAC_DEPARTMENT_ID"))) {
            //修改部门需要同步修改部门用户排序
            List<Map<String, Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPTUSER WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
            if (countList.size() <= 0) {
                countList = metaService.selectSql("SELECT MAX(DEPARTMENT_USER_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPARTMENT WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
            }
            int count = Integer.valueOf(countList.get(0).get("MAX_COUNT").toString());
            deptUserBean.set("SY_ORDERINDEX", count + 1);
        }

        //同步所属部门主管领导信息
        syncMajor(deptUserBean, deptBean, userBean, departmentId);

        if (!departmentId.equals(deptUser.getStr("JE_RBAC_DEPARTMENT_ID"))) {
            //若部门发生了改变，则调用变更部门
            JSONArray beanArr = new JSONArray();
            JSONObject beanObj = new JSONObject();
            beanObj.put("sourceDepartmentId", deptUser.getStr("JE_RBAC_DEPARTMENT_ID"));
            beanObj.put("targetDepartmentId", departmentId);
            beanObj.put("userId", deptUser.getStr("JE_RBAC_USER_ID"));
            //传递直属领导信息
            beanObj.put("type", "update");
            beanObj.put("directLeaderId", deptUserBean.getStr("DEPTUSER_DIRECTLEADER_ID"));
            beanObj.put("directLeaderName", deptUserBean.getStr("DEPTUSER_DIRECTLEADER_NAME"));
            beanArr.add(beanObj);
            changeDepartment(beanArr.toJSONString());
            //则更新 新部门人员数据，是否主管，直属领导
        } else {
            commonService.buildModelModifyInfo(deptUserBean);
            metaService.update(deptUserBean);
        }

        String currentRoleIds = userBean.getStr("USER_ROLE_ID");
        if (!(originalRoleIds == null ? "" : originalRoleIds).equals(currentRoleIds)) {
            DynaBean accountBean = metaService.selectOne("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().eq("USER_ASSOCIATION_ID", userId));
            if (accountBean != null) {
                rbacAccountRoleService.updateAccountRoles(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), originalRoleIds, currentRoleIds, deptBean.getStr("JE_RBAC_DEPARTMENT_ID"), deptBean.getStr("DEPARTMENT_NAME"), deptUserBean.getStr("DEPTUSER_MAIN_CODE"));
            }
        }

        return metaService.selectOne("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId)
                .eq("JE_RBAC_USER_ID", userBean.getStr("JE_RBAC_USER_ID")));
    }

    /***
     * 更新用户名称
     * @param deptUserBean
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateUserName(DynaBean deptUserBean) {
        DynaBean sourceUserBean = metaService.selectOne("JE_RBAC_USER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", deptUserBean.getStr("JE_RBAC_USER_ID")));
        if (!sourceUserBean.getStr("USER_NAME").equals(deptUserBean.getStr("USER_NAME"))) {
            //需要修改 公司表-管理员
            List<DynaBean> listManagerBean = metaService.select("JE_RBAC_COMPANY", ConditionsWrapper.builder().like("COMPANY_MANAGER_ID", "%" + deptUserBean.getStr("JE_RBAC_USER_ID") + "%"));
            if (listManagerBean != null && listManagerBean.size() > 0) {
                for (DynaBean eachCompanyBean : listManagerBean) {
                    List<String> managerIdList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MANAGER_ID").split(ArrayUtils.SPLIT));
                    List<String> managerNameList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MANAGER_NAME").split(ArrayUtils.SPLIT));
                    int indexCount = managerIdList.indexOf(deptUserBean.getStr("JE_RBAC_USER_ID"));
                    managerNameList.set(indexCount, deptUserBean.getStr("USER_NAME"));
                    metaService.executeSql("UPDATE JE_RBAC_COMPANY SET COMPANY_MANAGER_NAME={0} WHERE JE_RBAC_COMPANY_ID={1} ", StringUtils.join(managerNameList, ","), eachCompanyBean.getStr("JE_RBAC_COMPANY_ID"));
                }
            }

            //公司表-主管领导
            List<DynaBean> listBean = metaService.select("JE_RBAC_COMPANY", ConditionsWrapper.builder().like("COMPANY_MAJOR_ID", "%" + deptUserBean.getStr("JE_RBAC_USER_ID") + "%"));
            if (listBean != null && listBean.size() > 0) {
                for (DynaBean eachCompanyBean : listBean) {
                    List<String> zgIdList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MAJOR_ID").split(ArrayUtils.SPLIT));
                    List<String> zgNameList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MAJOR_NAME").split(ArrayUtils.SPLIT));
                    int indexCount = zgIdList.indexOf(deptUserBean.getStr("JE_RBAC_USER_ID"));
                    zgNameList.set(indexCount, deptUserBean.getStr("USER_NAME"));
                    metaService.executeSql("UPDATE JE_RBAC_COMPANY SET COMPANY_MAJOR_NAME={0} WHERE JE_RBAC_COMPANY_ID={1} ", StringUtils.join(zgNameList, ","), eachCompanyBean.getStr("JE_RBAC_COMPANY_ID"));
                }
            }

            //部门主管
            List<DynaBean> listDeptBean = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().like("DEPARTMENT_MAJOR_ID", "%" + deptUserBean.getStr("JE_RBAC_USER_ID") + "%"));
            if (listDeptBean != null && listDeptBean.size() > 0) {
                for (DynaBean eachBean : listDeptBean) {
                    List<String> zgIdList = Arrays.asList(eachBean.getStr("DEPARTMENT_MAJOR_ID").split(ArrayUtils.SPLIT));
                    List<String> zgNameList = Arrays.asList(eachBean.getStr("DEPARTMENT_MAJOR_NAME").split(ArrayUtils.SPLIT));
                    int indexCount = zgIdList.indexOf(deptUserBean.getStr("JE_RBAC_USER_ID"));
                    zgNameList.set(indexCount, deptUserBean.getStr("USER_NAME"));
                    metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_NAME={0} WHERE JE_RBAC_DEPARTMENT_ID={1} ", StringUtils.join(zgNameList, ","), eachBean.getStr("JE_RBAC_DEPARTMENT_ID"));
                }
            }

            //部门人员关联表（直接领导）
            metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET DEPTUSER_DIRECTLEADER_NAME={0} WHERE DEPTUSER_DIRECTLEADER_ID = {1}", deptUserBean.getStr("USER_NAME"), deptUserBean.getStr("JE_RBAC_USER_ID"));

            //todo 修改开发者人员名称

        }
    }

    /***
     * 修改部门用户信息时-同步所属部门主管领导信息
     * @param deptUserBean
     * @param deptBean
     * @param userBean
     * @param departmentId
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void syncMajor(DynaBean deptUserBean, DynaBean deptBean, DynaBean userBean, String departmentId) {
        //同步所属部门主管领导信息
        if (!Strings.isNullOrEmpty(deptUserBean.getStr("DEPTUSER_SFZG_CODE"))) {
            if (Strings.isNullOrEmpty(deptBean.getStr("DEPARTMENT_MAJOR_ID")) && deptUserBean.getStr("DEPTUSER_SFZG_CODE").equals("1")) {
                //更新部门主管信息
                metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", userBean.getStr("JE_RBAC_USER_ID"), userBean.getStr("USER_NAME"), departmentId);
            } else if (!Strings.isNullOrEmpty(deptBean.getStr("DEPARTMENT_MAJOR_ID"))) {
                //判断是否是主管,若 是主管
                if (deptUserBean.getStr("DEPTUSER_SFZG_CODE").equals("1")) {
                    //判断当前人是否在主管中，不在则追加
                    if (!deptBean.getStr("DEPARTMENT_MAJOR_ID").contains(userBean.getStr("JE_RBAC_USER_ID"))) {
                        List<String> majorIdList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_ID").split(ArrayUtils.SPLIT));
                        List<String> newMajorIdList = new ArrayList(majorIdList);
                        newMajorIdList.add(userBean.getStr("JE_RBAC_USER_ID"));
                        List<String> majorNameList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_NAME").split(ArrayUtils.SPLIT));
                        List<String> newMajorNameList = new ArrayList(majorNameList);
                        newMajorNameList.add(userBean.getStr("USER_NAME"));
                        metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", StringUtils.join(newMajorIdList, ","), StringUtils.join(newMajorNameList, ","), departmentId);
                    }
                } else {
                    //非主管，判断当前人是否在主管中，在则删除；
                    if (deptBean.getStr("DEPARTMENT_MAJOR_ID").contains(userBean.getStr("JE_RBAC_USER_ID"))) {
                        List<String> majorIdList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_ID").split(ArrayUtils.SPLIT));
                        List<String> newMajorIdList = new ArrayList(majorIdList);
                        newMajorIdList.remove(userBean.getStr("JE_RBAC_USER_ID"));
                        List<String> majorNameList = Arrays.asList(deptBean.getStr("DEPARTMENT_MAJOR_NAME").split(ArrayUtils.SPLIT));
                        List<String> newMajorNameList = new ArrayList(majorNameList);
                        newMajorNameList.remove(userBean.getStr("USER_NAME"));
                        metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", StringUtils.join(newMajorIdList, ","), StringUtils.join(newMajorNameList, ","), departmentId);
                    }
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void doUserRemove(String userDeptIds) throws DepartmentUserException {
        JSONArray array = JSONArray.parseArray(userDeptIds);
        if (array == null) {
            throw new DepartmentUserException("参数设置有误，请检查！");
        }
        List<Map<String, String>> mainDepartUserMapList = new ArrayList<>();
        List<Map<String, String>> otherDepartUserMapList = new ArrayList<>();

        for (int j = 0; j < array.size(); j++) {
            Map<String, String> mainDepartUserMap = new HashMap<>();
            Map<String, String> otherDepartUserMap = new HashMap<>();
            String departmentId = array.getJSONObject(j).getString("departmentId");
            String userId = array.getJSONObject(j).getString("userId");
            //部门类型：主，分
            String mainCode = array.getJSONObject(j).getString("mainCode");
            //判断人员是否是主部门 主部门与当前人的所有数据，全部删掉；若是分部门则只删除与分部门的关系
            if (mainCode.equals("1")) {
                //主部门
                mainDepartUserMap.put(departmentId, userId);
                mainDepartUserMapList.add(mainDepartUserMap);
            } else {
                otherDepartUserMap.put(departmentId, userId);
                otherDepartUserMapList.add(otherDepartUserMap);
            }
        }
        removeUsers(mainDepartUserMapList, otherDepartUserMapList);
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void doRemove(List<DynaBean> beanList) {
        List<Map<String, String>> mainDepartUserMapList = new ArrayList<>();
        List<Map<String, String>> otherDepartUserMapList = new ArrayList<>();
        if (beanList != null && beanList.size() > 0) {
            for (DynaBean eachBean : beanList) {
                Map<String, String> mainDepartUserMap = new HashMap<>();
                Map<String, String> otherDepartUserMap = new HashMap<>();
                //判断人员是否是主部门 主部门与当前人的所有数据，全部删掉；若是分部门则只删除与分部门的关系
                if (eachBean.getStr("DEPTUSER_MAIN_CODE").equals("1")) {
                    //主部门
                    mainDepartUserMap.put(eachBean.getStr("JE_RBAC_DEPARTMENT_ID"), eachBean.getStr("JE_RBAC_USER_ID"));
                    mainDepartUserMapList.add(mainDepartUserMap);
                } else {
                    otherDepartUserMap.put(eachBean.getStr("JE_RBAC_DEPARTMENT_ID"), eachBean.getStr("JE_RBAC_USER_ID"));
                    otherDepartUserMapList.add(otherDepartUserMap);
                }
            }
            removeUsers(mainDepartUserMapList, otherDepartUserMapList);
        }
    }

    @Override
    public void doDisableUser(List<DynaBean> deptUserList) {
        List<Map<String, String>> mainDepartUserMapList = new ArrayList<>();
        List<Map<String, String>> otherDepartUserMapList = new ArrayList<>();
        if (deptUserList != null && deptUserList.size() > 0) {
            for (DynaBean eachBean : deptUserList) {
                Map<String, String> mainDepartUserMap = new HashMap<>();
                Map<String, String> otherDepartUserMap = new HashMap<>();
                //判断人员是否是主部门 主部门与当前人的所有数据，全部删掉；若是分部门则只删除与分部门的关系
                if (eachBean.getStr("DEPTUSER_MAIN_CODE").equals("1")) {
                    //主部门
                    mainDepartUserMap.put(eachBean.getStr("JE_RBAC_DEPARTMENT_ID"), eachBean.getStr("JE_RBAC_USER_ID"));
                    mainDepartUserMapList.add(mainDepartUserMap);
                } else {
                    otherDepartUserMap.put(eachBean.getStr("JE_RBAC_DEPARTMENT_ID"), eachBean.getStr("JE_RBAC_USER_ID"));
                    otherDepartUserMapList.add(otherDepartUserMap);
                }
            }
            disableUsers(mainDepartUserMapList, otherDepartUserMapList);
        }
    }

    @Override
    public Department findDepartmentModel(String id) {
        return rbacDepartmentService.findDepartmentModelById(id);
    }

    @Override
    public DynaBean findDepartmentUserById(String departmentId, String userId) {
        return metaService.selectOne("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId)
                .eq("JE_RBAC_USER_ID", userId));
    }

    @Override
    public DynaBean findDepartmentUserByCode(String departmentId, String userCode) {
        return metaService.selectOne("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId)
                .eq("USER_CODE", userCode));
    }

    @Override
    public DynaBean findDepartmentUserByName(String departmentId, String userName) {
        return metaService.selectOne("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId)
                .eq("USER_NAME", userName));
    }

    @Override
    public DynaBean findDepartmentMajor(String departmentId, String userId) {
        return metaService.selectOne("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId)
                .eq("DEPTUSER_SFZG_CODE", "1"));
    }

    @Override
    public DynaBean findDepartmentDirectLeader(String departmentId, String userId) {
        DynaBean userBean = findDepartmentUserById(departmentId, userId);
        if (userBean == null) {
            return null;
        }
        return findDepartmentUserById(departmentId, userBean.getStr("DEPTUSER_DIRECTLEADER_ID"));
    }

    @Override
    public List<DynaBean> findCompanyUsers(String companyId) {
        return metaService.select("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("SY_COMPANY_ID", companyId));
    }

    @Override
    public List<DynaBean> findDepartmentUsers(String departmentId) {
        return metaService.select("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId));
    }

    @Override
    public List<DynaBean> findByTenantId(String tenantId) {
        return metaService.select("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("SY_TENANT_ID", tenantId));
    }

    @Override
    public List<DynaBean> findByTenantName(String tenantName) {
        return metaService.select("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder()
                .eq("SY_TENANT_NAME", tenantName));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void disableUsers(String userDeptIds) {
        JSONArray array = JSONArray.parseArray(userDeptIds);
        if (array != null && array.size() > 0) {
            List<Map<String, String>> mainDepartUserMapList = new ArrayList<>();
            List<Map<String, String>> otherDepartUserMapList = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                Map<String, String> mainDepartUserMap = new HashMap<>();
                Map<String, String> otherDepartUserMap = new HashMap<>();
                String departmentId = array.getJSONObject(i).getString("departmentId");
                String userId = array.getJSONObject(i).getString("userIds");
                String mainCode = array.getJSONObject(i).getString("mainCode");
                //判断人员是否是主部门 主部门与当前人的所有数据，全部禁用；若是分部门则只禁用与分部门的关系
                if (mainCode.equals("1")) {
                    mainDepartUserMap.put(departmentId, userId);
                    mainDepartUserMapList.add(mainDepartUserMap);
                } else {
                    otherDepartUserMap.put(departmentId, userId);
                    otherDepartUserMapList.add(otherDepartUserMap);
                }
            }
            disableUsers(mainDepartUserMapList, otherDepartUserMapList);
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void enableUsers(String departmentId, String userIds) {
        //人员关系
        List<String> userIdList = Arrays.asList(userIds.split(ArrayUtils.SPLIT));
        metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET SY_STATUS='1' WHERE JE_RBAC_DEPARTMENT_ID={0} AND JE_RBAC_USER_ID IN ({1})", departmentId, userIdList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void changeDepartment(String userDeptIds) throws DepartmentUserException {
        JSONArray array = JSONArray.parseArray(userDeptIds);
        for (int i = 0; i < array.size(); i++) {
            //源部门ID
            String sourceDepartmentId = array.getJSONObject(i).getString("sourceDepartmentId");
            //目标部门ID
            String targetDepartmentId = array.getJSONObject(i).getString("targetDepartmentId");
            //用户ID
            String userIdStr = array.getJSONObject(i).getString("userId");

            //type为 修改用户表单-修改部门时传参使用
            String type = array.getJSONObject(i).getString("type");

            //直属领导ID
            String directLeaderId = array.getJSONObject(i).getString("directLeaderId");

            //直属领导名称
            String directLeaderName = array.getJSONObject(i).getString("directLeaderName");

            if (Strings.isNullOrEmpty(type)) {
                //变更逻辑-需查询数据库直属领导字段值，同步变更
                DynaBean deptUserBean = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder()
                        .eq("JE_RBAC_DEPARTMENT_ID", sourceDepartmentId)
                        .eq("JE_RBAC_USER_ID", userIdStr));
                directLeaderId = deptUserBean.getStr("DEPTUSER_DIRECTLEADER_ID");
                directLeaderName = deptUserBean.getStr("DEPTUSER_DIRECTLEADER_NAME");
            }

            if (Strings.isNullOrEmpty(sourceDepartmentId)) {
                throw new DepartmentUserException("请选择源部门！");
            }
            if (Strings.isNullOrEmpty(targetDepartmentId)) {
                throw new DepartmentUserException("请选择目标部门！");
            }
            if (sourceDepartmentId.equals(targetDepartmentId)) {
                throw new DepartmentUserException("与当前部门重复，请重新选择！");
            }
            if (Strings.isNullOrEmpty(userIdStr)) {
                throw new DepartmentUserException("请选择人员！");
            }
            DynaBean userBean = metaService.selectOne("JE_RBAC_USER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userIdStr));
            if (userBean == null) {
                throw new DepartmentUserException("不存在的人员，请确认！");
            }
            DynaBean deptBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", targetDepartmentId));
            if (deptBean == null) {
                throw new DepartmentUserException("不存在的部门，请确认！");
            }

            DynaBean accountBean = metaService.selectOne("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().eq("USER_ASSOCIATION_ID", userIdStr));

            //查询目标部门是否存在
            DynaBean targetDeptBean = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder()
                    .eq("JE_RBAC_DEPARTMENT_ID", targetDepartmentId)
                    .eq("JE_RBAC_USER_ID", userIdStr)
                    .eq("DEPTUSER_MAIN_CODE", "0"));

            //变更自己分部门为 主部门情况
            if (targetDeptBean != null) {
                //删除此人员原来的部门关系
                deleteDeptUser(sourceDepartmentId, userIdStr);
                if (accountBean!=null) {

                    //查询目标部门是否开通账号，若开通则删除原账号相关的部门，角色数据；只需变更主分关系
                    DynaBean targetAccountDept = metaService.selectOne("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().eq("ACCOUNTDEPT_ACCOUNT_ID", accountBean.getStr("JE_RBAC_ACCOUNT_ID")).eq("ACCOUNTDEPT_DEPT_ID", targetDepartmentId));


                    if (targetAccountDept != null) {
                        //删除此人员原来的账号部门关系
                        deleteUserDept(sourceDepartmentId, accountBean.getStr("JE_RBAC_ACCOUNT_ID"));

                        //删除此人员原来的 角色账号部门关系
                        deleteUserRole(sourceDepartmentId, accountBean.getStr("JE_RBAC_ACCOUNT_ID"), userBean.getStr("USER_ROLE_ID"));
                    } else {
                        //没有开通访问，并且没有其他部门开通，则删除原来的账号；否则保留。
                        //只有原部门、目标部门的账号部门信息；并且目标部门，没有点击允许访问系统 生成账号部门信息
                        //部门用户有数据
                        //账号部门关系
                        //角色账号部门关系

                        //修改此人员原来的账号部门关系 改为目标节点的
                        updateUserDept(sourceDepartmentId, targetDepartmentId, accountBean.getStr("JE_RBAC_ACCOUNT_ID"));

                        //修改此人员原来的 角色账号部门关系 改为目标节点的
                        updateUserRole(sourceDepartmentId, targetDepartmentId, accountBean.getStr("JE_RBAC_ACCOUNT_ID"), userBean.getStr("USER_ROLE_ID"));

                    }
                    //变更目标部门，角色账号部门关系 展示为主部门
                    metaService.executeSql("UPDATE JE_RBAC_ACCOUNTROLE SET ACCOUNTROLE_MAIN_CODE ='1' WHERE ACCOUNTROLE_ACCOUNT_ID = {0} AND ACCOUNTROLE_DEPT_ID = {1} ", accountBean.getStr("JE_RBAC_ACCOUNT_ID"), targetDepartmentId);
                    //变更主分关系 //则更新 新部门人员数据，是否主管，直属领导
                    metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET DEPTUSER_MAIN_CODE='1',DEPTUSER_MAIN_NAME = '主部门',DEPTUSER_DIRECTLEADER_ID={0},DEPTUSER_DIRECTLEADER_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID = {2} AND JE_RBAC_USER_ID = {3}", directLeaderId, directLeaderName, targetDepartmentId, userIdStr);
                }
            } else {
                DynaBean deptUserBean = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder()
                        .eq("JE_RBAC_DEPARTMENT_ID", sourceDepartmentId)
                        .eq("JE_RBAC_USER_ID", userIdStr));

                //删除此人员原来的部门关系
                deleteDeptUser(sourceDepartmentId, userIdStr);

                if (accountBean != null) {

                    //部门关系没有
                    deptUserBean.setStr("JE_RBAC_DEPARTMENT_ID",targetDepartmentId);
                    commonService.buildModelCreateInfo(deptUserBean);
                    metaService.insert(deptUserBean);
                    //修改此人员原来的账号部门关系 改为目标节点的
                    updateUserDept(sourceDepartmentId, targetDepartmentId, accountBean.getStr("JE_RBAC_ACCOUNT_ID"));

                    //修改此人员原来的 角色账号部门关系 改为目标节点的
                    updateUserRole(sourceDepartmentId, targetDepartmentId, accountBean.getStr("JE_RBAC_ACCOUNT_ID"), userBean.getStr("USER_ROLE_ID"));

                }
                //变更为其他部门
//                insertMainUserDept(userIdStr, directLeaderId, directLeaderName, deptBean);
            }

        }
    }

    private void updateUserRole(String sourceDepartmentId, String targetDepartmentId, String accountId, String roleIds) {
        List<String> roleIdsList = Arrays.asList(roleIds.split(ArrayUtils.SPLIT));
        if (accountId != null && roleIdsList.size() > 0) {
            //修改此人员原来的 角色账号部门关系
            DynaBean dynaBean = metaService.selectOneByPk("JE_RBAC_DEPARTMENT", targetDepartmentId);
            String deptName = dynaBean==null ? "" :dynaBean.getStr("DEPARTMENT_NAME");
            metaService.executeSql("update JE_RBAC_ACCOUNTROLE set ACCOUNTROLE_DEPT_ID = '"+targetDepartmentId+"' , ACCOUNTROLE_DEPT_NAME = '"+deptName+"' where " +
                    "ACCOUNTROLE_ACCOUNT_ID = '"+accountId+"' and ACCOUNTROLE_DEPT_ID = '"+sourceDepartmentId+"' and ACCOUNTROLE_ROLE_ID in ({0})",roleIdsList);
        }

    }

    private void updateUserDept(String sourceDepartmentId, String targetDepartmentId, String accountId) {
        DynaBean sourceAccountDept = metaService.selectOne("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().eq("ACCOUNTDEPT_ACCOUNT_ID", accountId).eq("ACCOUNTDEPT_DEPT_ID", sourceDepartmentId));
        if (sourceAccountDept != null) {
            //修改此人员原来的账号部门关系
            sourceAccountDept.setStr("ACCOUNTDEPT_DEPT_ID",targetDepartmentId);
            DynaBean dynaBean = metaService.selectOneByPk("JE_RBAC_DEPARTMENT", targetDepartmentId);
            sourceAccountDept.setStr("ACCOUNTDEPT_DEPT_NAME",dynaBean==null ? "" :dynaBean.getStr("DEPARTMENT_NAME"));
            metaService.update("JE_RBAC_ACCOUNTDEPT","JE_RBAC_ACCOUNTDEPT_ID", sourceAccountDept,ConditionsWrapper.builder().eq("JE_RBAC_ACCOUNTDEPT_ID", sourceAccountDept.getStr("JE_RBAC_ACCOUNTDEPT_ID")));
        }

    }

    /***
     * 添加部门为 用户主部门
     * @param userIdStr     用户id
     * @param deptBean      部门信息
     */
    public void insertMainUserDept(String userIdStr, String directLeaderId, String directLeaderName, DynaBean deptBean) {
        //处理人员排序字段
        List<Map<String, Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPTUSER WHERE JE_RBAC_DEPARTMENT_ID ='" + deptBean.getStr("JE_RBAC_DEPARTMENT_ID") + "'");
        if (countList.size() <= 0) {
            countList = metaService.selectSql("SELECT MAX(DEPARTMENT_USER_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPARTMENT WHERE JE_RBAC_DEPARTMENT_ID ='" + deptBean.getStr("JE_RBAC_DEPARTMENT_ID") + "'");
        }
        int count = Integer.valueOf(countList.get(0).get("MAX_COUNT").toString());
        DynaBean companyBean = metaService.selectOne("JE_RBAC_COMPANY", ConditionsWrapper.builder().eq("JE_RBAC_COMPANY_ID", deptBean.getStr("SY_COMPANY_ID")));

        //添加当前部门为用户的主部门
        DynaBean needAddDeptUserBean = new DynaBean("JE_RBAC_DEPTUSER", false);
        needAddDeptUserBean.set("JE_RBAC_DEPARTMENT_ID", deptBean.getStr("JE_RBAC_DEPARTMENT_ID"));
        needAddDeptUserBean.set("JE_RBAC_USER_ID", userIdStr);
        needAddDeptUserBean.set("DEPTUSER_MAIN_CODE", "1");
        needAddDeptUserBean.set("DEPTUSER_MAIN_NAME", "主部门");
        needAddDeptUserBean.set("SY_COMPANY_ID", deptBean.getStr("SY_COMPANY_ID"));
        needAddDeptUserBean.set("SY_COMPANY_NAME", deptBean.getStr("SY_COMPANY_NAME"));
        needAddDeptUserBean.set("SY_COMPANY_CODE", companyBean.getStr("COMPANY_CODE"));
        needAddDeptUserBean.set("SY_GROUP_COMPANY_ID", deptBean.getStr("SY_GROUP_COMPANY_ID"));
        needAddDeptUserBean.set("SY_GROUP_COMPANY_NAME", deptBean.getStr("SY_GROUP_COMPANY_NAME"));
        needAddDeptUserBean.set("SY_TENANT_ID", deptBean.getStr("SY_TENANT_ID"));
        needAddDeptUserBean.set("SY_TENANT_NAME", deptBean.getStr("SY_TENANT_NAME"));
        needAddDeptUserBean.setStr("SY_STATUS", "0");
        needAddDeptUserBean.set("DEPTUSER_MAJOR_ID", deptBean.getStr("DEPARTMENT_MAJOR_ID"));
        needAddDeptUserBean.set("DEPTUSER_MAJOR_NAME", deptBean.getStr("DEPARTMENT_MAJOR_NAME"));
        if (deptBean.getStr("DEPARTMENT_MAJOR_ID").contains(userIdStr)) {
            needAddDeptUserBean.set("DEPTUSER_SFZG_CODE", "1");
            needAddDeptUserBean.set("DEPTUSER_SFZG_NAME", "是");
        } else {
            needAddDeptUserBean.set("DEPTUSER_SFZG_CODE", "0");
            needAddDeptUserBean.set("DEPTUSER_SFZG_NAME", "否");
        }
        needAddDeptUserBean.set("DEPTUSER_DIRECTLEADER_ID", directLeaderId);
        needAddDeptUserBean.set("DEPTUSER_DIRECTLEADER_NAME", directLeaderName);
        needAddDeptUserBean.set("SY_ORDERINDEX", count + 1);
        needAddDeptUserBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
        metaService.insert(needAddDeptUserBean);
    }

    public void deleteDeptUser(String deptId, String userId) {
        metaService.delete("JE_RBAC_DEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", deptId)
                .eq("JE_RBAC_USER_ID", userId));
    }

    public void deleteUserDept(String deptId, String accountId) {
        DynaBean sourceAccountDept = metaService.selectOne("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().eq("ACCOUNTDEPT_ACCOUNT_ID", accountId).eq("ACCOUNTDEPT_DEPT_ID", deptId));
        if (sourceAccountDept != null) {
            //删除此人员原来的账号部门关系
            metaService.delete("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().eq("JE_RBAC_ACCOUNTDEPT_ID", sourceAccountDept.getStr("JE_RBAC_ACCOUNTDEPT_ID")));
        }
    }

    public void deleteUserRole(String deptId, String accountid, String roleIds) {
        List<String> roleIdsList = Arrays.asList(roleIds.split(ArrayUtils.SPLIT));
        if (accountid != null && roleIdsList != null && roleIdsList.size() > 0) {
            //删除此人员原来的 角色账号部门关系
            metaService.delete("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder()
                    .eq("ACCOUNTROLE_ACCOUNT_ID", accountid)
                    .eq("ACCOUNTROLE_DEPT_ID", deptId)
                    .in("ACCOUNTROLE_ROLE_ID", roleIdsList));
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void openAccount(String userDeptIds) throws AccountException {
        JSONArray array = JSONArray.parseArray(userDeptIds);
        for (int j = 0; j < array.size(); j++) {
            String departmentId = array.getJSONObject(j).getString("departmentId");
            String userId = array.getJSONObject(j).getString("userId");
            //部门类型：主，分
            String mainCode = array.getJSONObject(j).getString("mainCode");

            rbacAccountService.checkAccountUnique(userId, array.size());

            String syStatus = "1";
            if (!Strings.isNullOrEmpty(array.getJSONObject(j).getString("status"))) {
                //创建用户调用传参，账号默认禁用
                syStatus = array.getJSONObject(j).getString("status");
            }

            DynaBean userBean = metaService.selectOne("JE_RBAC_USER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userId));

            //需判断该人员所属部门状态
            DynaBean department = rbacDepartmentService.findById(departmentId);
            if (department == null) {
                throw new AccountException("该部门不存在！");
            }
            //判断当前所属部门是主部门，分部门），
            // 若所属部门是主部门被禁用，则不允许操作给提示；
            // 若当前是 分部门（被禁用，则给提示先启用，再去判断主部门状态））
            if ((mainCode.equals("1") || mainCode.equals("0")) && department.getStr("SY_STATUS").equals("0")) {
                //主部门,分部门被禁用
                if (array.size() == 1) {
                    throw new AccountException("该员工的上级部门已被禁用，请先启用！");
                } else {
                    throw new AccountException("该员工【" + userBean.getStr("USER_NAME") + "】的上级部门已被禁用，请先启用！");
                }
            } else if (mainCode.equals("0") && department.getStr("SY_STATUS").equals("1")) {
                //分部门正常，则去判断当前用户主部门是否被禁用

                //判断主部门是否已经允许访问了，若已经允许，则分部门可以允许访问；若主部门没有允许访问，则提示 请先操作主部门允许访问。
                DynaBean userMainDeptBean = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userId).eq("DEPTUSER_MAIN_CODE", "1"));
                if (!rbacDepartmentUserService.checkMainDeptStatusById(userId)) {
                    if (array.size() == 1) {
                        throw new AccountException("该员工主部门的访问状态已被禁用，请先启用！");
                    } else {
                        throw new AccountException("请先开启该员工【" + userBean.getStr("USER_NAME") + "】主部门的访问状态！");
                    }
                }

                //userid查询相关账号，然后查询是否有主部门关联的账号。
                List<DynaBean> accountBeanList = metaService.select("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().eq("USER_ASSOCIATION_ID", userId));
                List<String> accountIds = new ArrayList<>();
                for (DynaBean accountBean : accountBeanList) {
                    accountIds.add(accountBean.getStr("JE_RBAC_ACCOUNT_ID"));
                }
                DynaBean accountMainDeptBean = metaService.selectOne("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().eq("ACCOUNTDEPT_DEPT_ID", userMainDeptBean.getStr("JE_RBAC_DEPARTMENT_ID")).in("ACCOUNTDEPT_ACCOUNT_ID", accountIds));
                if (accountMainDeptBean == null) {
                    if (array.size() == 1) {
                        throw new AccountException("当前用户主部门未开通账号，请先开通当前用户主部门账号！");
                    } else {
                        throw new AccountException("当前用户【" + userBean.getStr("USER_NAME") + "】主部门未开通账号，请先开通当前用户主部门账号！");
                    }

                }
            }
            if (syStatus.equals("1")) {
                //更改为允许访问
                enableUsers(departmentId, userId);
            }

            DynaBean orgBean = metaService.selectOne("JE_RBAC_ORG", ConditionsWrapper.builder()
                    .eq("JE_RBAC_ORG_ID", OrgType.DEPARTMENT_ORG_ID.getCode()));
            if (orgBean == null) {
                throw new AccountException("不存在部门机构！");
            }
            //获取到映射的资源表和资源表主键
            String tableCode = orgBean.getStr("ORG_RESOURCETABLE_CODE");
            String tableIdCode = orgBean.getStr("ORG_FIELD_PK");
            if (Strings.isNullOrEmpty(tableCode) || Strings.isNullOrEmpty(tableIdCode)) {
                throw new AccountException("Can't find the tableCode or pk code from the org mapping!");
            }

            //获取映射字段，账号名称、账号编码、账号手机、账号邮箱、账号头像
            String accountNameField = orgBean.getStr("ORG_ACCOUNT_NAME");
            String accountCodeField = orgBean.getStr("ORG_ACCOUNT_CODE");
            String accountPhoneField = orgBean.getStr("ORG_ACCOUNT_PHONE");
            String accountEmailField = orgBean.getStr("ORG_ACCOUNT_MAIL");
            String accountSexField = orgBean.getStr("ORG_ACCOUNT_SEX");
            String accountAvatarField = orgBean.getStr("ORG_ACCOUNT_AVATAR");
            String accountUserStatusField = orgBean.getStr("ORG_ACCOUNT_STATUS");
            String accountSecretCodeField = orgBean.getStr("ORG_SECRET_CODE");
            String accountSecretNameField = orgBean.getStr("ORG_SECRET_NAME");

            String defaultPassword = systemSettingRpcService.findSettingValue("JE_SYS_PASSWORD");
            if (Strings.isNullOrEmpty(defaultPassword)) {
                throw new AccountException("系统设置默认密码为空！");
            }

            DynaBean departmentBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", departmentId));
            if (departmentBean == null) {
                throw new AccountException("不存在的部门！");
            }

            List<DynaBean> accountBeanList = metaService.select("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("USER_ASSOCIATION_ID", userId));
            List<String> accountIds = new ArrayList<>();
            if (accountBeanList != null && accountBeanList.size() > 0) {
                for (DynaBean dynaBean : accountBeanList) {
                    accountIds.add(dynaBean.getStr("JE_RBAC_ACCOUNT_ID"));
                }
                metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_STATUS='1' WHERE JE_RBAC_ACCOUNT_ID IN ({0})", accountIds);
                metaService.executeSql("UPDATE JE_RBAC_ACCOUNTDEPT SET SY_STATUS='1' WHERE ACCOUNTDEPT_DEPT_ID = {0} AND ACCOUNTDEPT_ACCOUNT_ID IN ({1})", departmentId, accountIds);
            }
            Map<String, DynaBean> hasAccountMap = new HashMap<>();
            for (DynaBean eachAccountBean : accountBeanList) {
                hasAccountMap.put(eachAccountBean.getStr("USER_ASSOCIATION_ID"), eachAccountBean);
            }

            List<DynaBean> userBeans = metaService.select(tableCode, ConditionsWrapper.builder().in(tableIdCode, userId));
            DynaBean accountBean;
            String accountId;
            List<DynaBean> accountDeptRoleModelList = new ArrayList<>();
            for (DynaBean eachUserBean : userBeans) {
                if (hasAccountMap.containsKey(eachUserBean.getStr(tableIdCode))) {
                    accountId = hasAccountMap.get(eachUserBean.getStr(tableIdCode)).getStr("JE_RBAC_ACCOUNT_ID");
                } else {
                    accountId = JEUUID.uuid();
                    accountBean = new DynaBean("JE_RBAC_ACCOUNT", true);
                    accountBean.set("JE_RBAC_ACCOUNT_ID", accountId);
                    accountBean.set("ACCOUNT_NAME", eachUserBean.getStr(accountNameField));
                    accountBean.set("ACCOUNT_CODE", eachUserBean.getStr(accountCodeField));
                    accountBean.set("ACCOUNT_OPENID", JEUUID.uuid());
                    accountBean.set("ACCOUNT_PASSWORD", SecureUtil.md5(defaultPassword));
                    accountBean.set("ACCOUNT_PHONE", eachUserBean.getStr(accountPhoneField));
                    accountBean.set("ACCOUNT_MAIL", eachUserBean.getStr(accountEmailField));
                    accountBean.set("ACCOUNT_SEX", eachUserBean.getStr(accountSexField));
                    accountBean.set("ACCOUNT_AVATAR", eachUserBean.getStr(accountAvatarField));
                    accountBean.set("USER_ASSOCIATION_ID", eachUserBean.getStr(tableIdCode));
                    accountBean.set("ACCOUNT_REMARK", "通过部门人员创建！");
                    accountBean.set("SY_ORG_ID", orgBean.getStr("JE_RBAC_ORG_ID"));
                    accountBean.set("SY_ORG_NAME", orgBean.getStr("ORG_NAME"));
                    accountBean.set("SY_STATUS", syStatus);
                    accountBean.set("USER_STATUS", eachUserBean.getStr(accountUserStatusField));
                    accountBean.set("ACCOUNT_LOCKED_STATUS", "1");
                    //永久使用
                    accountBean.set("ACCOUNT_PERMANENT_CODE", "1");
                    //过期时间
                    accountBean.set("ACCOUNT_EXPIRE_TIME", "");
                    //密级
                    accountBean.set("SY_SECRET_CODE",eachUserBean.getStr("SY_SECRET_CODE"));
                    accountBean.set("SY_SECRET_NAME",eachUserBean.getStr("SY_SECRET_NAME"));
                    commonService.buildModelCreateInfo(accountBean);
                    metaService.insert(accountBean);
                }
//                rbacAccountService.checkAccountUnique(eachUserBean.getStr(tableIdCode),userBeans.size());

                rbacAccountService.insertAccountDept(accountId, departmentId, syStatus);

                String roleIds = eachUserBean.getStr("USER_ROLE_ID");
                String roleNames = eachUserBean.getStr("USER_ROLE_NAME");
                if (Strings.isNullOrEmpty(roleIds) || Strings.isNullOrEmpty(roleNames)) {
                    continue;
                }

                List<String> roleIdList = Splitter.on(",").splitToList(roleIds);
                List<String> roleNameList = Splitter.on(",").splitToList(roleNames);

                DynaBean accountDeptRoleTempBean;
                for (int i = 0; i < roleIdList.size(); i++) {
                    int sysOrderIndex = -1;
                    List<Map<String, Object>> userOrderList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_ACCOUNTROLE WHERE ACCOUNTROLE_ROLE_ID={0}", roleIdList.get(i));
                    if (userOrderList.size() > 0) {
                        sysOrderIndex = Integer.valueOf(userOrderList.get(0).get("MAX_COUNT").toString());
                    }
                    sysOrderIndex = (sysOrderIndex + 1);
                    accountDeptRoleTempBean = new DynaBean("JE_RBAC_ACCOUNTROLE", false);
                    accountDeptRoleTempBean.set("ACCOUNTROLE_ACCOUNT_ID", accountId);
                    accountDeptRoleTempBean.set("ACCOUNTROLE_DEPT_ID", departmentId);
                    accountDeptRoleTempBean.set("ACCOUNTROLE_DEPT_NAME", departmentBean.getStr("DEPARTMENT_NAME"));
                    accountDeptRoleTempBean.set("ACCOUNTROLE_MAIN_CODE", mainCode);
                    accountDeptRoleTempBean.set("ACCOUNTROLE_ROLE_ID", roleIdList.get(i));
                    accountDeptRoleTempBean.set("ACCOUNTROLE_ROLE_NAME", roleNameList.get(i));
                    accountDeptRoleTempBean.set("SY_ORDERINDEX", sysOrderIndex);
                    accountDeptRoleTempBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
                    accountDeptRoleModelList.add(accountDeptRoleTempBean);
                }
            }

            List<String> accountIdList = new ArrayList<>();
            for (DynaBean eachBean : accountDeptRoleModelList) {
                accountIdList.add(eachBean.getStr("ACCOUNTROLE_ACCOUNT_ID"));
            }

            List<DynaBean> existsAccountDeptRoleList = metaService.select("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder()
                    .in("ACCOUNTROLE_ACCOUNT_ID", accountIdList)
                    .eq("ACCOUNTROLE_DEPT_ID", departmentId));
            List<DynaBean> needRemovedBeanList = new ArrayList<>();
            for (DynaBean eachExistsBean : existsAccountDeptRoleList) {
                for (DynaBean eachNeedInsertBean : accountDeptRoleModelList) {
                    if (eachExistsBean.getStr("ACCOUNTROLE_ACCOUNT_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_ACCOUNT_ID"))
                            && eachExistsBean.getStr("ACCOUNTROLE_DEPT_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_DEPT_ID"))
                            && eachExistsBean.getStr("ACCOUNTROLE_ROLE_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_ROLE_ID"))) {
                        needRemovedBeanList.add(eachNeedInsertBean);
                    }
                }
            }
            accountDeptRoleModelList.removeAll(needRemovedBeanList);
            metaService.insertBatch("JE_RBAC_ACCOUNTROLE", accountDeptRoleModelList);
        }
    }

    @Override
    public Boolean checkMainDeptStatusById(String userId) {
        DynaBean deptUsertBean = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userId).eq("DEPTUSER_MAIN_CODE", "1"));
        if (deptUsertBean.getStr("SY_STATUS").equals("0")) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void operationOnTheJob(String userIds) {
        List<String> userIdList = Arrays.asList(userIds.split(ArrayUtils.SPLIT));
        metaService.executeSql("UPDATE JE_RBAC_USER SET USER_EMPLOYEE_STATUS='1' WHERE JE_RBAC_USER_ID IN ({0})", userIdList);
        metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET USER_STATUS='1' WHERE USER_ASSOCIATION_ID IN ({0})", userIdList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void operationQuitJob(String userIds) {
        List<String> userIdList = Arrays.asList(userIds.split(ArrayUtils.SPLIT));
        metaService.executeSql("UPDATE JE_RBAC_USER SET USER_EMPLOYEE_STATUS='0',SY_STATUS='0' WHERE JE_RBAC_USER_ID IN ({0})", userIdList);
        metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET SY_STATUS='0' WHERE JE_RBAC_USER_ID IN ({0})", userIdList);
        //当该人员为离职状态，禁用该人员下所有账号
        List<DynaBean> inAccountList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder().in("USER_ASSOCIATION_ID", userIdList));
        List<String> disableAccountList = new ArrayList<>();
        for (DynaBean eachDepartmentAccountBean : inAccountList) {
            disableAccountList.add(eachDepartmentAccountBean.getStr("JE_RBAC_ACCOUNT_ID"));
        }
        if (disableAccountList != null && disableAccountList.size() > 0) {
            metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_STATUS='0',USER_STATUS='0' WHERE JE_RBAC_ACCOUNT_ID IN ({0})", disableAccountList);
            metaService.executeSql("UPDATE JE_RBAC_ACCOUNTDEPT SET SY_STATUS='0' WHERE ACCOUNTDEPT_ACCOUNT_ID IN ({0})", disableAccountList);
        }
    }

    @Override
    public JSONTreeNode loadAccountPermissionTree(String userIds) throws DepartmentUserException {
        List<String> userIdList = Splitter.on(",").splitToList(userIds);
        DynaBean accountBean = metaService.selectOne("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("USER_ASSOCIATION_ID", userIdList));
        if (accountBean == null) {
            throw new DepartmentUserException("该人员下无相关操作账号！");
        }
        JSONTreeNode root = rbacGrantTreeService.loadAccountMenuPermissions(accountBean.getStr("JE_RBAC_ACCOUNT_ID"));
        return root;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, DepartmentUserException.class})
    public void userAgeCalculation() throws DepartmentUserException {
        List<DynaBean> userBeanList = metaService.select("JE_RBAC_USER", ConditionsWrapper.builder());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int currentYear = calendar.get(Calendar.YEAR);

        if (userBeanList == null) {
            throw new DepartmentUserException("请选择需要操作的人员！");
        }
        try {
            for (DynaBean eachUserBean : userBeanList) {
                if (!Strings.isNullOrEmpty(eachUserBean.getStr("USER_BIRTH"))) {
                    calendar.setTime(sdf.parse(eachUserBean.getStr("USER_BIRTH")));
                    int birthYear = calendar.get(Calendar.YEAR);
                    int age = (currentYear - birthYear);
                    metaService.executeSql("UPDATE JE_RBAC_USER SET USER_AGE={0} WHERE JE_RBAC_USER_ID ={1}", age, eachUserBean.getStr("JE_RBAC_USER_ID"));
                }
            }
        } catch (ParseException e) {
            throw new DepartmentUserException("年龄计算失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public long userResetPassword(String userIds) throws AccountException, DepartmentUserException {
        List<String> userIdList = Arrays.asList(userIds.split(ArrayUtils.SPLIT));
        String defaultPassword = systemSettingRpcService.findSettingValue("JE_SYS_PASSWORD");
        List<DynaBean> accountBeanList = metaService.select("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("USER_ASSOCIATION_ID", userIdList));
        if (accountBeanList == null || accountBeanList.size() <= 0) {
            throw new DepartmentUserException("该员工还未创建账号，不能重置密码，请先开通账号！");
        }
        List<String> accountIds = new ArrayList<>();
        int count = 0;
        for (DynaBean eachAccountBean : accountBeanList) {
            accountIds.add(eachAccountBean.getStr("JE_RBAC_ACCOUNT_ID"));
        }
        count = metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET ACCOUNT_PASSWORD={0} WHERE JE_RBAC_ACCOUNT_ID IN ({1})", SecureUtil.md5(defaultPassword), accountIds);
        return count;
    }


    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public long userUnlock(String userIds) throws DepartmentUserException {
        List<String> userIdList = Arrays.asList(userIds.split(ArrayUtils.SPLIT));
        List<DynaBean> accountBeanList = metaService.select("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("USER_ASSOCIATION_ID", userIdList));
        if (accountBeanList == null) {
            throw new DepartmentUserException("请选择需要操作的人员！");
        }
        List<String> accountIdList = new ArrayList<>();
        int count = 0;
        for (DynaBean eachAccountBean : accountBeanList) {
            accountIdList.add(eachAccountBean.getStr("JE_RBAC_ACCOUNT_ID"));
        }
        count = metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET ACCOUNT_LOCKED_STATUS ='1', ACCOUNT_LOCK_EXPIRE = '' WHERE JE_RBAC_ACCOUNT_ID IN ({0})", accountIdList);
        return count;
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void disableAccount(String departmentId, String userIds) {
        List<String> userIdList = Arrays.asList(userIds.split(ArrayUtils.SPLIT));
//        //更改为禁止访问
//        disableUsers(departmentId,userIds);

        //禁用账号，账号存在其他部门的，不应该被禁用
        List<DynaBean> inAccountList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder()
                .eq("ACCOUNTDEPT_DEPT_ID", departmentId).in("USER_ASSOCIATION_ID", userIdList));
        List<String> disableAccountList = new ArrayList<>();
        for (DynaBean eachDepartmentAccountBean : inAccountList) {
            disableAccountList.add(eachDepartmentAccountBean.getStr("JE_RBAC_ACCOUNT_ID"));
        }

        List<DynaBean> allAccountList = metaService.select("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_DEPT_ID", disableAccountList));
        for (DynaBean eachAccountBean : allAccountList) {
            if (!departmentId.equals(eachAccountBean.getStr("ACCOUNTDEPT_DEPT_ID"))) {
                disableAccountList.remove(eachAccountBean.getStr("ACCOUNTDEPT_ACCOUNT_ID"));
            }
        }
        metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_STATUS='0' WHERE JE_RBAC_ACCOUNT_ID IN ({0})", disableAccountList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void enableAccount(String userIds) {
        List<String> userIdList = Splitter.on(",").splitToList(userIds);
        metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_STATUS='1' WHERE USER_ASSOCIATION_ID IN ({0})", StringUtil.buildArrayToString(userIdList));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void removeUsers(List<Map<String, String>> mainDepartUserMapList, List<Map<String, String>> otherDepartUserMapList) {
        //当前人员所属部门为主部门删除逻辑
        if (mainDepartUserMapList != null && mainDepartUserMapList.size() > 0) {
            for (Map<String, String> mainDepartUserMap : mainDepartUserMapList) {
                for (Map.Entry entry : mainDepartUserMap.entrySet()) {
                    String deptId = entry.getKey().toString();
                    String userId = entry.getValue().toString();
                    List<DynaBean> inAccountList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder()
                            .eq("ACCOUNTDEPT_DEPT_ID", deptId).in("USER_ASSOCIATION_ID", userId));
                    metaService.delete("JE_RBAC_DEPTUSER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userId));
                    metaService.delete("JE_RBAC_USER", ConditionsWrapper.builder().eq("JE_RBAC_USER_ID", userId));
                    // 全局同步移除该员工信息
                    syncRemoveUserMsg(userId);
                    List<String> disableAccountList = new ArrayList<>();
                    for (DynaBean eachDepartmentAccountBean : inAccountList) {
                        disableAccountList.add(eachDepartmentAccountBean.getStr("JE_RBAC_ACCOUNT_ID"));
                    }
                    List<DynaBean> allAccountList = metaService.select("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_ACCOUNT_ID", disableAccountList));
                    List<String> allAccountIdList = new ArrayList<>();
                    for (DynaBean eachAccountBean : allAccountList) {
                        allAccountIdList.add(eachAccountBean.getStr("ACCOUNTDEPT_ACCOUNT_ID"));
                    }
                    if (allAccountIdList != null && allAccountIdList.size() > 0) {
                        metaService.delete("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_ACCOUNT_ID", allAccountIdList));
                        metaService.delete("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("JE_RBAC_ACCOUNT_ID", allAccountIdList));
                        metaService.delete("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder().in("ACCOUNTROLE_ACCOUNT_ID", allAccountIdList));
                    }
                }
            }
        }
        if (otherDepartUserMapList != null && otherDepartUserMapList.size() > 0) {
            for (Map<String, String> otherDepartUserMap : otherDepartUserMapList) {
                //当前人员所属部门为分部门删除逻辑
                for (Map.Entry entry : otherDepartUserMap.entrySet()) {
                    String userId = entry.getValue().toString();
                    String deptId = entry.getKey().toString();

                    List<DynaBean> inAccountList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder()
                            .eq("ACCOUNTDEPT_DEPT_ID", deptId).in("USER_ASSOCIATION_ID", userId));
                    metaService.delete("JE_RBAC_DEPTUSER", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", deptId).eq("JE_RBAC_USER_ID", userId));
                    List<String> disableAccountList = new ArrayList<>();
                    for (DynaBean eachDepartmentAccountBean : inAccountList) {
                        disableAccountList.add(eachDepartmentAccountBean.getStr("JE_RBAC_ACCOUNT_ID"));
                    }
                    if (disableAccountList != null && disableAccountList.size() > 0) {
                        metaService.delete("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().eq("ACCOUNTDEPT_DEPT_ID", deptId).in("ACCOUNTDEPT_ACCOUNT_ID", disableAccountList));
                        metaService.delete("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder().eq("ACCOUNTROLE_DEPT_ID", deptId).in("ACCOUNTROLE_ACCOUNT_ID", disableAccountList));
                    }
                }
            }

        }
    }

    /***
     * 移除该人员-全局同步更新移除该人员信息数据
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void syncRemoveUserMsg(String userId) {
        //公司表-管理员
        updateCompanyUserManager(userId);
        //部门人员关联表-直属领导
        metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET DEPTUSER_DIRECTLEADER_ID={0},DEPTUSER_DIRECTLEADER_NAME={1} WHERE DEPTUSER_DIRECTLEADER_ID={2} ", "", "", userId);
        //公司表-主管领导
        updateCompanyUserJgField(userId);
        //部门表-主管领导
        updateDeptUserJgField(userId);
        //todo 需同步移除开发者选项
    }

    /***
     * 公司表-管理员-同步更新去除该员工信息
     * @param userId
     */
    @Transactional(rollbackFor = RuntimeException.class)
    void updateCompanyUserManager(String userId) {
        List<DynaBean> listManagerBean = metaService.select("JE_RBAC_COMPANY", ConditionsWrapper.builder().like("COMPANY_MANAGER_ID", "%" + userId + "%"));
        if (listManagerBean != null && listManagerBean.size() > 0) {
            for (DynaBean eachCompanyBean : listManagerBean) {
                List<String> managerIdList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MANAGER_ID").split(ArrayUtils.SPLIT));
                List<String> managerNameList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MANAGER_NAME").split(ArrayUtils.SPLIT));
                int indexCount = managerIdList.indexOf(userId);
                managerIdList.set(indexCount,"");
                managerNameList.set(indexCount, "");
                managerIdList = managerIdList.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
                managerNameList = managerNameList.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
                metaService.executeSql("UPDATE JE_RBAC_COMPANY SET COMPANY_MANAGER_NAME={0} , COMPANY_MANAGER_ID={1} WHERE JE_RBAC_COMPANY_ID={2} ", StringUtils.join(managerNameList, ","), StringUtils.join(managerIdList, ","), eachCompanyBean.getStr("JE_RBAC_COMPANY_ID"));
            }
        }
    }

    /***
     * 部门表-主管领导-同步更新去除该员工信息
     * @param userId
     */
    @Transactional(rollbackFor = RuntimeException.class)
    void updateDeptUserJgField(String userId) {
        List<Map<String, Object>> listDeptBeanMap = findAllUserJGDeptById(userId);
        List<String> idList = Splitter.on(",").splitToList(userId);
        for (Map<String, Object> eachBeanMap : listDeptBeanMap) {
            //主管Id
            List<String> jgIdList = Arrays.asList(eachBeanMap.get("DEPARTMENT_MAJOR_ID").toString().split(ArrayUtils.SPLIT));
            List<String> newGgIdList = new ArrayList(jgIdList);
            List<String> indexData = new ArrayList<>();
            for (String deptId : idList) {
                if (jgIdList.indexOf(deptId) >= 0) {
                    //记录要删除的下标
                    indexData.add(jgIdList.indexOf(deptId) + "");
                    newGgIdList.remove(deptId);
                }
            }
            //主管名称
            List<String> jgNameList = Arrays.asList(eachBeanMap.get("DEPARTMENT_MAJOR_NAME").toString().split(ArrayUtils.SPLIT));
            List<String> newGgNameList = new ArrayList(jgNameList);
            for (String eachIndex : indexData) {
                newGgNameList.remove(Integer.parseInt(eachIndex));
            }
            metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_ID={0},DEPARTMENT_MAJOR_NAME={1} WHERE JE_RBAC_DEPARTMENT_ID={2} ", StringUtils.join(newGgIdList, ","), StringUtils.join(newGgNameList, ","), eachBeanMap.get("JE_RBAC_DEPARTMENT_ID"));
        }
    }

    /***
     * 公司表-主管领导-同步更新去除该员工信息
     * @param userId
     */
    @Transactional(rollbackFor = RuntimeException.class)
    void updateCompanyUserJgField(String userId) {
        List<Map<String, Object>> listDeptBeanMap = findCompanyAllUserJGDeptById(userId);
        List<String> idList = Splitter.on(",").splitToList(userId);
        for (Map<String, Object> eachBeanMap : listDeptBeanMap) {
            //主管Id
            List<String> jgIdList = Arrays.asList(eachBeanMap.get("COMPANY_MAJOR_ID").toString().split(ArrayUtils.SPLIT));
            List<String> newGgIdList = new ArrayList(jgIdList);
            List<String> indexData = new ArrayList<>();
            for (String deptId : idList) {
                if (jgIdList.indexOf(deptId) >= 0) {
                    //记录要删除的下标
                    indexData.add(jgIdList.indexOf(deptId) + "");
                    newGgIdList.remove(deptId);
                }
            }
            //主管名称
            List<String> jgNameList = Arrays.asList(eachBeanMap.get("COMPANY_MAJOR_NAME").toString().split(ArrayUtils.SPLIT));
            List<String> newGgNameList = new ArrayList(jgNameList);
            for (String eachIndex : indexData) {
                newGgNameList.remove(Integer.parseInt(eachIndex));
            }
            metaService.executeSql("UPDATE JE_RBAC_COMPANY SET COMPANY_MAJOR_ID={0},COMPANY_MAJOR_NAME={1} WHERE JE_RBAC_COMPANY_ID={2} ", StringUtils.join(newGgIdList, ","), StringUtils.join(newGgNameList, ","), eachBeanMap.get("JE_RBAC_COMPANY_ID"));
        }
    }

    /***
     * 部门表-查询所有该员工作为主管的部门数据
     * @param userId
     * @return
     */
    private List<Map<String, Object>> findAllUserJGDeptById(String userId) {
        List<String> idList = Splitter.on(",").splitToList(userId);
        StringBuilder deptSqlBuffer = new StringBuilder("SELECT * FROM JE_RBAC_DEPARTMENT WHERE ");
        String[] params = new String[idList.size()];
        for (int i = 0; i < idList.size(); i++) {
            if (i == 0) {
                deptSqlBuffer.append(" DEPARTMENT_MAJOR_ID LIKE {" + i + "}");
            } else {
                deptSqlBuffer.append(" OR DEPARTMENT_MAJOR_ID LIKE {" + i + "}");
            }
            params[i] = "%" + idList.get(i) + "%";
        }
        List<Map<String, Object>> deptBeans = metaService.selectSql(deptSqlBuffer.toString(), params);
        return deptBeans;
    }

    /***
     * 公司表-查询所有该员工作为主管的部门数据
     * @param userId
     * @return
     */
    private List<Map<String, Object>> findCompanyAllUserJGDeptById(String userId) {
        List<String> idList = Splitter.on(",").splitToList(userId);
        StringBuilder deptSqlBuffer = new StringBuilder("SELECT * FROM JE_RBAC_COMPANY WHERE ");
        String[] params = new String[idList.size()];
        for (int i = 0; i < idList.size(); i++) {
            if (i == 0) {
                deptSqlBuffer.append(" COMPANY_MAJOR_ID LIKE {" + i + "}");
            } else {
                deptSqlBuffer.append(" OR COMPANY_MAJOR_ID LIKE {" + i + "}");
            }
            params[i] = "%" + idList.get(i) + "%";
        }
        List<Map<String, Object>> deptBeans = metaService.selectSql(deptSqlBuffer.toString(), params);
        return deptBeans;
    }


    @Transactional(rollbackFor = RuntimeException.class)
    public void disableUsers(List<Map<String, String>> mainDepartUserMapList, List<Map<String, String>> otherDepartUserMapList) {
        //当前人员所属部门为主部门禁用逻辑
        if (mainDepartUserMapList != null && mainDepartUserMapList.size() > 0) {
            for (Map<String, String> mapObj : mainDepartUserMapList) {
                for (Map.Entry entry : mapObj.entrySet()) {
                    String deptId = entry.getKey().toString();
                    String userId = entry.getValue().toString();
                    metaService.executeSql("UPDATE JE_RBAC_USER SET SY_STATUS='0' WHERE JE_RBAC_USER_ID IN ({0})", userId);
                    metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET SY_STATUS='0' WHERE  JE_RBAC_USER_ID = {0}", userId);

                    List<DynaBean> inAccountList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder()
                            .eq("ACCOUNTDEPT_DEPT_ID", deptId).in("USER_ASSOCIATION_ID", userId));
                    List<String> disableAccountList = new ArrayList<>();
                    for (DynaBean eachDepartmentAccountBean : inAccountList) {
                        disableAccountList.add(eachDepartmentAccountBean.getStr("JE_RBAC_ACCOUNT_ID"));
                    }
                    List<DynaBean> allAccountList = metaService.select("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_ACCOUNT_ID", disableAccountList));
                    List<String> allAccountIdList = new ArrayList<>();
                    for (DynaBean eachAccountBean : allAccountList) {
                        allAccountIdList.add(eachAccountBean.getStr("ACCOUNTDEPT_ACCOUNT_ID"));
                    }
                    if (allAccountIdList != null && allAccountIdList.size() > 0) {
                        metaService.executeSql("UPDATE JE_RBAC_ACCOUNTDEPT SET SY_STATUS='0' WHERE ACCOUNTDEPT_ACCOUNT_ID IN ({0})", allAccountIdList);
                        metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_STATUS='0' WHERE JE_RBAC_ACCOUNT_ID IN ({0})", allAccountIdList);
                    }
                }
            }

        }
        if (otherDepartUserMapList != null && otherDepartUserMapList.size() > 0) {
            for (Map<String, String> mapObj : otherDepartUserMapList) {
                //当前人员所属部门为分部门禁用逻辑
                for (Map.Entry entry : mapObj.entrySet()) {
                    String userId = entry.getValue().toString();
                    String deptId = entry.getKey().toString();
                    metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET SY_STATUS='0' WHERE JE_RBAC_DEPARTMENT_ID = {0} AND JE_RBAC_USER_ID = {1}", deptId, userId);

                    List<DynaBean> inAccountList = metaService.select("JE_RBAC_VACCOUNTDEPT", ConditionsWrapper.builder()
                            .eq("ACCOUNTDEPT_DEPT_ID", deptId).in("USER_ASSOCIATION_ID", userId));
                    List<String> disableAccountList = new ArrayList<>();
                    for (DynaBean eachDepartmentAccountBean : inAccountList) {
                        disableAccountList.add(eachDepartmentAccountBean.getStr("JE_RBAC_ACCOUNT_ID"));
                    }
                    if (disableAccountList != null && disableAccountList.size() > 0) {
                        metaService.executeSql("UPDATE JE_RBAC_ACCOUNTDEPT SET SY_STATUS='0' WHERE ACCOUNTDEPT_DEPT_ID = {0} AND ACCOUNTDEPT_ACCOUNT_ID IN ({1})", deptId, disableAccountList);
                    }
                }
            }
        }
    }

    @Override
    public DynaBean findDirectLeaderBean(String departmentId, String userId) {
        DynaBean deptUserBean = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId).eq("JE_RBAC_USER_ID", userId));
        if (deptUserBean == null) {
            return null;
        }
        return deptUserBean;
    }

    @Override
    public String findDirectLeader(String departmentId, String userId) {
        DynaBean deptUserBean = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder()
                .eq("JE_RBAC_DEPARTMENT_ID", departmentId).eq("JE_RBAC_USER_ID", userId));
        if (deptUserBean == null) {
            return null;
        }
        return deptUserBean.getStr("DEPTUSER_DIRECTLEADER_ID");
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, DepartmentUserException.class})
    public void addOtherDepartment(String userDeptIds) throws DepartmentUserException {

        JSONArray array = JSONArray.parseArray(userDeptIds);
        for (int i = 0; i < array.size(); i++) {
            //分部门ID
            String departmentId = array.getJSONObject(i).getString("departmentId");
            String userId = array.getJSONObject(i).getString("userIds");
            //需判断该人员所属部门状态
            DynaBean department = rbacDepartmentService.findById(departmentId);
            if (department == null) {
                throw new DepartmentUserException("当前部门不存在！");
            }
            //查找当前用户主部门
            DynaBean deptUserBean = metaService.selectOne("JE_RBAC_DEPTUSER", ConditionsWrapper.builder().eq("DEPTUSER_MAIN_CODE", "1").in("JE_RBAC_USER_ID", userId));
            //判断当前用户主部门与所选分部门是否一样。若一样则返回
            if (deptUserBean == null) {
                throw new DepartmentUserException("不存在的部门！");
            }
            if (deptUserBean.getStr("JE_RBAC_DEPARTMENT_ID").equals(departmentId)) {
                throw new DepartmentUserException("您选择的部门为员工主部门，请重新选择！");
            }
            //查找当前分部门
            DynaBean departmentBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", departmentId));
            if (departmentBean == null) {
                throw new DepartmentUserException("不存在的部门！");
            }
            List<DynaBean> userBeanList = metaService.select("JE_RBAC_USER", ConditionsWrapper.builder().in("JE_RBAC_USER_ID", userId));
            List<DynaBean> deptUserBeanList = metaService.select("JE_RBAC_DEPTUSER", ConditionsWrapper.builder().in("JE_RBAC_USER_ID", userId));
            List<DynaBean> eachDeptUserBeanList;
            for (DynaBean eachUserBean : userBeanList) {
                eachDeptUserBeanList = new ArrayList<>();
                for (DynaBean eachDeptUserBean : deptUserBeanList) {
                    if (eachUserBean.getStr("JE_RBAC_USER_ID").equals(eachDeptUserBean.getStr("JE_RBAC_USER_ID"))) {
                        eachDeptUserBeanList.add(eachDeptUserBean);
                    }
                }
                if (eachDeptUserBeanList != null && eachDeptUserBeanList.size() > 0) {
                    //遍历当前用户的所有部门，查找是否已经是分部门
                    Boolean falg = false;
                    for (DynaBean eachBean : eachDeptUserBeanList) {
                        if (eachBean.getStr("JE_RBAC_DEPARTMENT_ID").equals(departmentId) && eachBean.getStr("DEPTUSER_MAIN_CODE").equals("0")) {
                            throw new DepartmentUserException("该员工已在此部门中，请重新选择！");
                        }
                    }
                    List<Map<String, Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPTUSER WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
                    if (countList.size() <= 0) {
                        countList = metaService.selectSql("SELECT MAX(DEPARTMENT_USER_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_DEPARTMENT WHERE JE_RBAC_DEPARTMENT_ID ='" + departmentId + "'");
                    }
                    int count = Integer.valueOf(countList.get(0).get("MAX_COUNT").toString());
                    //添加当前部门为用户的分部门
                    DynaBean needAddDeptUserBean = new DynaBean("JE_RBAC_DEPTUSER", false);
                    needAddDeptUserBean.set("JE_RBAC_DEPARTMENT_ID", departmentId);
                    needAddDeptUserBean.set("JE_RBAC_USER_ID", eachUserBean.getStr("JE_RBAC_USER_ID"));
                    needAddDeptUserBean.set("DEPTUSER_MAIN_CODE", "0");
                    needAddDeptUserBean.set("DEPTUSER_MAIN_NAME", "分部门");
                    needAddDeptUserBean.set("SY_COMPANY_ID", departmentBean.getStr("SY_COMPANY_ID"));
                    needAddDeptUserBean.set("SY_COMPANY_NAME", departmentBean.getStr("SY_COMPANY_NAME"));
                    DynaBean companyBean = metaService.selectOne("JE_RBAC_COMPANY", ConditionsWrapper.builder().in("JE_RBAC_COMPANY_ID", departmentBean.getStr("SY_COMPANY_ID")));
                    needAddDeptUserBean.set("SY_COMPANY_CODE", companyBean.getStr("COMPANY_CODE"));
                    needAddDeptUserBean.set("SY_GROUP_COMPANY_ID", departmentBean.getStr("SY_GROUP_COMPANY_ID"));
                    needAddDeptUserBean.set("SY_GROUP_COMPANY_NAME", departmentBean.getStr("SY_GROUP_COMPANY_NAME"));
                    needAddDeptUserBean.set("SY_TENANT_ID", departmentBean.getStr("SY_TENANT_ID"));
                    needAddDeptUserBean.set("SY_TENANT_NAME", departmentBean.getStr("SY_TENANT_NAME"));
                    needAddDeptUserBean.setStr("SY_STATUS", "0");
                    if (departmentBean.getStr("DEPARTMENT_MAJOR_ID")!=null && departmentBean.getStr("DEPARTMENT_MAJOR_ID").contains(eachUserBean.getStr("JE_RBAC_USER_ID"))) {
                        needAddDeptUserBean.set("DEPTUSER_SFZG_CODE", "1");
                        needAddDeptUserBean.set("DEPTUSER_SFZG_NAME", "是");
                    } else {
                        needAddDeptUserBean.set("DEPTUSER_SFZG_CODE", "0");
                        needAddDeptUserBean.set("DEPTUSER_SFZG_NAME", "否");
                        needAddDeptUserBean.set("DEPTUSER_MAJOR_ID", departmentBean.getStr("DEPARTMENT_MAJOR_ID"));
                        needAddDeptUserBean.set("DEPTUSER_MAJOR_NAME", departmentBean.getStr("DEPARTMENT_MAJOR_NAME"));
                    }
                    needAddDeptUserBean.set("SY_ORDERINDEX", count + 1);
                    needAddDeptUserBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
                    metaService.insert(needAddDeptUserBean);
                } else {
                    //当前用户没有部门，则记录错误；
                    continue;
                }
            }
        }
    }

    @Override
    public JSONTreeNode findOrgStructureAndBuildTreeNode() {
        JSONTreeNode companyNode = rbacDepartmentService.buildCompanyTreeData(false);
        List<DynaBean> userDepts = metaService.select("JE_RBAC_VDEPTUSER", ConditionsWrapper.builder().orderByAsc("SY_ORDERINDEX"));
        recursiveDeptUserTreeNode(companyNode, userDepts);
        return companyNode;
    }


    /***
     * 构建部门账号
     * @param rootNode
     * @param userDepts
     */
    private void recursiveDeptUserTreeNode(JSONTreeNode rootNode, List<DynaBean> userDepts) {
        if ("department".equals(rootNode.getNodeInfoType())) {
            JSONTreeNode node;
            for (DynaBean userDeptBean : userDepts) {
                if (!rootNode.getId().equals(userDeptBean.getStr("JE_RBAC_DEPARTMENT_ID"))) {
                    continue;
                }
                parseUserDepartmentToTree(rootNode, userDeptBean);
            }
        }
        if (rootNode.getChildren() == null || rootNode.getChildren().isEmpty()) {
            return;
        }
        for (JSONTreeNode eachChildNode : rootNode.getChildren()) {
            recursiveDeptUserTreeNode(eachChildNode, userDepts);
        }
    }

    /**
     * 解析部门账号信息为tree
     *
     * @param resultJSONTreeNode
     * @param user
     */
    public static void parseUserDepartmentToTree(JSONTreeNode resultJSONTreeNode, DynaBean user) {
        JSONTreeNode node = new JSONTreeNode();
        node.setId(user.getStr("JE_RBAC_DEPTUSER_ID"));
        node.setCode(user.getStr("USER_CODE"));
        node.setText(user.getStr("USER_NAME"));
        node.setNodeType("LEAF");
        node.setNodeInfoType("user");
        node.setIcon(IconType.TCONTYPE_ROLE.getVal());
        node.setParent(resultJSONTreeNode.getId());
        node.setLayer(resultJSONTreeNode.getLayer() + 1);
        node.setOrderIndex(user.getStr("SY_ORDERINDEX"));
        node.setBean(user.getValues());
        resultJSONTreeNode.getChildren().add(node);
    }


    @Override
    @Transactional(rollbackFor = {RuntimeException.class, DepartmentUserException.class})
    public void moveDeptUser(String id, String told, String place) throws DepartmentUserException {
        DynaBean deptUserBean = metaService.selectOneByPk("JE_RBAC_DEPTUSER", id);
        List<DynaBean> deptUserBeanList = metaService.select("JE_RBAC_DEPTUSER",
                ConditionsWrapper.builder()
                        .eq("JE_RBAC_DEPARTMENT_ID", deptUserBean.getStr("JE_RBAC_DEPARTMENT_ID"))
                        .orderByAsc("SY_ORDERINDEX"));
        //查出该部门下所有员工
        int minCount = Integer.valueOf(deptUserBeanList.get(0).getStr("SY_ORDERINDEX"));
        for (int i = 0; i < deptUserBeanList.size(); i++) {
            if (deptUserBeanList.get(i).getStr("JE_RBAC_DEPTUSER_ID").equals(id)) {
                deptUserBeanList.remove(i);
            }
        }
        List<DynaBean> newDynaBeanList = new ArrayList<>();
        if ("above".equals(place)) {
            //目标节点上面：先放入集合移动节点，查找目标节点下面（包含目标节点）的数据再放入是，然后重排；按照该部门内数据orderIndex最小值
            for (DynaBean eachBean : deptUserBeanList) {
                if (eachBean.getStr("JE_RBAC_DEPTUSER_ID").equals(told)) {
                    newDynaBeanList.add(deptUserBean);
                }
                newDynaBeanList.add(eachBean);
            }
            //重新排序
            for (DynaBean eachBean : newDynaBeanList) {
                eachBean.setStr("SY_ORDERINDEX", minCount + "");
                minCount++;
            }
        } else if ("below".equals(place)) {
            //目标节点下面：查找目标节点，再放入移动节点，然后重排；按照该部门内数据orderIndex最小值
            for (DynaBean eachBean : deptUserBeanList) {
                newDynaBeanList.add(eachBean);
                if (eachBean.getStr("JE_RBAC_DEPTUSER_ID").equals(told)) {
                    newDynaBeanList.add(deptUserBean);
                }
            }
            //重新排序
            for (DynaBean eachBean : newDynaBeanList) {
                eachBean.setStr("SY_ORDERINDEX", minCount + "");
                minCount++;
            }
        }
        //更新
        for (DynaBean eachChildBean : newDynaBeanList) {
            metaService.update(eachChildBean);
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, DepartmentUserException.class})
    public void moveDept(String id, String told, String place) throws DepartmentUserException {
        DynaBean deptBean = metaService.selectOneByPk("JE_RBAC_DEPARTMENT", id);
        List<DynaBean> deptBeanList = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().orderByAsc("SY_ORDERINDEX"));
        if (deptBeanList == null || deptBeanList.size() <= 0) {
            throw new DepartmentUserException("排序失败！");
        }
        int minCount = Integer.valueOf(deptBeanList.get(0).getStr("SY_ORDERINDEX"));
        for (int i = 0; i < deptBeanList.size(); i++) {
            if (deptBeanList.get(i).getStr("JE_RBAC_DEPARTMENT_ID").equals(id)) {
                deptBeanList.remove(i);
            }
        }
        List<DynaBean> newDynaBeanList = new ArrayList<>();
        if ("above".equals(place)) {
            //目标节点上面
            for (DynaBean eachBean : deptBeanList) {
                if (eachBean.getStr("JE_RBAC_DEPARTMENT_ID").equals(told)) {
                    newDynaBeanList.add(deptBean);
                }
                newDynaBeanList.add(eachBean);
            }
            //重新排序
            for (DynaBean eachBean : newDynaBeanList) {
                eachBean.set("SY_ORDERINDEX", minCount);
                minCount = minCount + 10000;
            }
        } else if ("below".equals(place)) {
            //目标节点下面
            for (DynaBean eachBean : deptBeanList) {
                newDynaBeanList.add(eachBean);
                if (eachBean.getStr("JE_RBAC_DEPARTMENT_ID").equals(told)) {
                    newDynaBeanList.add(deptBean);
                }
            }
            //重新排序
            for (DynaBean eachBean : newDynaBeanList) {
                eachBean.set("SY_ORDERINDEX", minCount);
                minCount = minCount + 10000;
            }
        }
        //更新
        for (DynaBean eachChildBean : newDynaBeanList) {
            metaService.update(eachChildBean);
            //更新部门用户orderIndex
            List<DynaBean> deptList = metaService.select("JE_RBAC_DEPTUSER", ConditionsWrapper.builder()
                    .eq("JE_RBAC_DEPARTMENT_ID", eachChildBean.getStr("JE_RBAC_DEPARTMENT_ID")).orderByAsc("SY_ORDERINDEX"));
            int i = 0;
            for (DynaBean deptUser : deptList) {
                int syOrderIndex = Integer.valueOf(eachChildBean.get("SY_ORDERINDEX").toString()) + i;
                deptUser.set("SY_ORDERINDEX", syOrderIndex);
                metaService.update(deptUser);
                i++;
            }
        }
    }

}

